<template>
	<view v-if="isRouterAlive">
		<Header :title="t('management.mapManagement')" />
		<view class="box" v-if="deviceMapList.length && !isLoading">
			<up-swipe-action
				v-for="(item, index) in deviceMapList"
				:key="index">
				<up-swipe-action-item
					:options="options2"
					@click="operateClick($event, item)"
					:disabled="item.property === 1">
					<view class="content" @click="openMap(item)">
						<up-avatar
							shape="square"
							size="57"
							class="avatar"
							src="/static/image/device/map.png"></up-avatar>
						<view class="right">
							<up-text
								:text="item.map_info?.map_name"
								size="17"
								color="#333"
								bold></up-text>
							<up-text
								v-if="getMapAreaTotal(item.zone_info.zones)"
								:text="` ${t(
									'map.allArea'
								)}： ${getMapAreaTotal(
									item.zone_info.zones
								)}m²`"
								style="margin-top: 10rpx"
								size="12"
								color="#adadad"></up-text>
						</view>
						<view class="default-box" v-if="item.property === 1">
							<view class="dot">{{ t("default") }}</view>
						</view>
					</view>
				</up-swipe-action-item>
			</up-swipe-action>
		</view>
		<view class="loading" v-show="isLoading">
			<LoadingDots />
		</view>
		<up-empty
			v-if="!deviceMapList.length && !isLoading"
			icon="/static/image/common/noData.svg"
			width="35%"
			textSize="18"
			text-color="#b8b8b8"
			safeAreaInsetBottom
			:text="t('noList')"></up-empty>
		<TipsModal
			v-if="showTip"
			type="nomal"
			:contentText="t('isDeleteMap')"
			@handleCancel="cancelTip"
			@handleConfirm="handleDeleteMap" />
		<up-popup
			v-model:show="showMap"
			@close="closeMap"
			:safeAreaInsetBottom="false"
			mode="bottom"
			:round="0">
			<view class="map-top">
				<text>{{ t("map.name") }}：</text>
				<text class="black">{{ mapItem?.map_info.map_name }}</text>
				<span v-if="getMapAreaTotal(mapItem?.zone_info.zones)">
					<text>{{ t("map.allArea") }}：</text>
					<text class="black">
						{{ getMapAreaTotal(mapItem?.zone_info.zones) }}m²
					</text>
				</span>
			</view>
			<view class="map-bottom">
				<Map
					:mapUrl="mapItem.map_info.map_docs[0].oss_url"
					type="manage" />
			</view>
		</up-popup>
	</view>
</template>

<script setup lang="ts">
import Header from "@/components/header/index.vue";
import { onMounted, reactive, ref, getCurrentInstance, nextTick } from "vue";
import { useI18n } from "vue-i18n";
import { useDeviceStore } from "@/stores/device";
import { useDevice } from "@/utils/device";
import Map from "@/components/Map/index.vue";
import {
	changeMapDefault,
	getDeviceShadowApi,
	delDeviceMap,
} from "@/service/index";
import { onLoad, onPullDownRefresh } from "@dcloudio/uni-app";
import LoadingDots from "@/components/LoadingDots/index.vue";
import TipsModal from "@/components/tipsModal/index.vue";
const { getDeviceMaps } = useDevice();
const deviceStore = useDeviceStore();
const deviceStatus = ref<number | null>(null);
const conn_status = ref<number | null>(null);
const { locale, t } = useI18n();
const device_sn = ref("");
const isLoading = ref(false);
const deviceMapList = ref<DeviceMap[]>([]);
const instance: any = getCurrentInstance();
const showMap = ref(false);
const mapItem = ref<DeviceMap>();
const options2 = reactive([
	{
		text: t("default"),
		style: {
			backgroundColor: "rgb(0, 82, 249)",
		},
	},
	{
		text: t("delete"),
		style: {
			backgroundColor: "rgb(247, 98, 96)",
		},
	},
]);
const showTip = ref(false);
const isRouterAlive = ref(true);
const reload = () => {
	isRouterAlive.value = false;
	nextTick(() => {
		isRouterAlive.value = true;
	});
};
const cancelTip = () => {
	showTip.value = false;
};
const closeMap = () => {
	showMap.value = false;
};
const openMap = (item: any) => {
	mapItem.value = item;
	showMap.value = true;
};
//计算区域面积总和
const getMapAreaTotal = (zones: Array<{ area: number | string }>): number => {
	return zones.reduce((total, zone) => {
		const areaValue =
			typeof zone.area === "string" ? parseFloat(zone.area) : zone.area;
		return total + (isNaN(areaValue) ? 0 : areaValue);
	}, 0);
};
const handleSetDefaultMap = async (item: MapInfo) => {
	// 获取设备状态
	const shadowResponse = await getDeviceShadowApi({
		device_sn: device_sn.value,
	});
	const shadowData = shadowResponse.data;

	if (shadowData && !shadowData.code) {
		deviceStatus.value = shadowData.data.status;
		conn_status.value = shadowData.data.conn_status;
	}
	// 检查连接状态
	if (conn_status.value !== 1) {
		instance.proxy.$message(t("setMapInfo1"), "warning");
		return;
	}
	// 检查设备状态
	if (deviceStatus.value !== 1 && deviceStatus.value !== 4) {
		instance.proxy.$message(t("setMapInfo2"), "warning");
		return;
	}
	// 设置默认地图
	const { data } = await changeMapDefault({
		device_sn: device_sn.value,
		map_id: item.map_info.map_id,
	});
	if (data.code === 0) {
		instance.proxy.$message(t("setDefaultSuccess"), "success");
		// 2秒后跳转
		setTimeout(() => {
			uni.redirectTo({
				url: "/pages/device/index" + `?device_sn=${device_sn.value}`,
			});
		}, 2000);
	} else {
		instance.proxy.$message(data.msg || t("setDefaultFailed"), "warning");
	}
};
const init = async () => {
	isLoading.value = true;
	await getDeviceMaps(device_sn.value, "manage");
	deviceMapList.value = deviceStore.deviceMapList;
	isLoading.value = false;
};
const mapId = ref("");
// 删除地图
const handleDeleteMap = async () => {
	const response = await delDeviceMap({
		map_id: mapId.value,
		device_sn: device_sn.value,
	});

	if (response.data.code === 0) {
		instance.proxy.$message(t("deleteOk"), "success");
		reload();
	}
	showTip.value = false;
};
const operateClick = (e: any, item: MapInfo) => {
	if (e.index == 0) {
		handleSetDefaultMap(item);
	} else {
		showTip.value = true;
		mapId.value = item.map_info.map_id;
	}
};
//下拉刷新
onPullDownRefresh(() => {
	setTimeout(() => {
		init();
		uni.stopPullDownRefresh();
	}, 1500);
});
onLoad((options) => {
	if (options?.device_sn) {
		device_sn.value = options.device_sn;
		init();
	}
});
onMounted(() => {});
</script>

<style lang="scss" scoped>
.loading {
	height: 100vh;
	background-color: #d8d8d8;
}
.box {
	padding: 20rpx;
	.u-swipe-action {
		box-shadow: 0px 1px 4px 1px rgba(0, 0, 0, 0.2);
		border-radius: 5px;
		position: relative;
		margin-bottom: 20rpx;
	}
	.u-swipe-action-item {
		border-radius: 5px;
	}
	.content {
		padding: 20rpx;
		padding-bottom: 12px;
		overflow: hidden;
		display: flex;
		gap: 10px;
		align-items: center;
		.default-box {
			position: absolute;
			right: 0;
			top: 0;
			width: 72px;
			background: #3370ff;
			color: #fff;
			text-align: center;
			height: 28px;
			line-height: 28px;
			border-top-left-radius: 14px;
			font-size: 16px;
			.dot {
				padding-left: 10px;
			}
			.dot:before {
				content: " ";
				width: 7px;
				height: 7px;
				background: #fff;
				border-radius: 7px;
				position: absolute;
				left: 10px;
				top: 10px;
			}
		}
	}
}
:deep(.u-slide-up-enter-active) {
	/* #ifdef H5 */
	bottom: 0 !important;
	/* #endif */
}
:deep(.u-fade-enter-active) {
	/* #ifdef H5 */
	bottom: 0 !important;
	/* #endif */
}
.map-top {
	padding: 20rpx;
	font-size: 14px;
	color: #999;
	.black {
		color: #333;
	}
	span {
		margin-left: 20rpx;
	}
}
.map-bottom {
	height: 70vh;
	overflow: hidden;
	background-color: #cdcdcd;
}
</style>
